package com.loopj.android.http.util;

import org.apache.http.Header;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 请求与逻辑处理中间层
 * 
 * @author xindaoapp
 * 
 */
public class RequestQueue {
	public static AsyncHttpClient client = new AsyncHttpClient();

	public void add(MoccaRequest request) {
		if (request.requestType.equals("POST")) {
			post(request);
		} else {
			get(request);
		}
	}

	public void get(final MoccaRequest moccaRequest) {

		client.get(moccaRequest.url, moccaRequest.params, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
				moccaRequest.parse(statusCode, headers, responseBody);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
				moccaRequest.errorListener.onErrorResponse(null);
			}
		});
	}

	public void post(final MoccaRequest moccaRequest) {
		if (null != moccaRequest.getHeaders()) {
			Header[] headers = moccaRequest.getHeaders();
			for (int i = 0; i < headers.length; i++) {
				client.addHeader(headers[i].getName(), headers[i].getValue());
			}
		}
		client.post(null, moccaRequest.url, moccaRequest.params, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
				moccaRequest.parse(statusCode, headers, responseBody);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
				moccaRequest.errorListener.onErrorResponse(null);
			}
		});
	}

}
